<template>
  <Form style="margin-bottom: 5px">
    <Row :gutter="15">
      <Col :span="6">
        <Form.Item label="截止日期">
          <Select v-model:value="currentTime" :options="times" @change="changeTime" />
        </Form.Item>
      </Col>
    </Row>
  </Form>
  <Table :columns="columns" :scroll="{ x: 800, y: contentHeight -80 }" :pagination="false" :data-source="holders" size="small" bordered></Table>
</template>
<script setup>
  import { ref, h, inject, watchEffect, reactive, onMounted } from 'vue';
  import { Form, Row, Col, Select, Table } from 'ant-design-vue';

  import { friendlyNumbers } from '@/libs/helpers.js';

  const props = defineProps({
    code: {
      type: String
    },
    contentHeight: {
      type: Number
    }
  });

  const $http = inject('$http');

  const times = ref([]);
  const holders = ref([]);
  const currentTime = ref('');

  const columns = reactive([
    { title: '股东名称', dataIndex: 'holder_name', width: 300, ellipsis: true },
    { title: '持股数量', width: 100, ellipsis: true, customRender: ({ record }) => friendlyNumbers(record.held_num) },
    { title: '持股比例', width: 60, ellipsis: true, customRender: ({ record }) => record.held_ratio + '%' },
    {
      title: '较上期变动',
      width: 60,
      ellipsis: true,
      customRender: ({ record }) => {
        if (record.chg == 0) {
          return '不变';
        } else {
          return h(
            'span',
            {
              style: {
                color: (record.chg || 1) > 0 ? '#ed4014' : '#19be6b'
              }
            },
            record.chg == null ? '新进股东' : record.chg + '%'
          );
        }
      }
    }
  ]);

  function loadTopHolders() {
    $http.get(`/api/shares/${props.code}/topholder`).then(res => {
      times.value = (res.data.times || []).map(t => {
        return { label: t.name, value: t.value };
      });

      holders.value = res.data.items;

      currentTime.value = times.value[0].value;
    });
  }

  function changeTime(start) {
    $http.get(`/api/shares/${props.code}/topholder?start=${currentTime.value}`).then(res => {
      holders.value = res.data.items;
    });
  }

  onMounted(() => {
    loadTopHolders();
  });

  watchEffect(() => {
    loadTopHolders();
  });
</script>
